import 'package:flutter/material.dart';
import '../database/database_helper.dart';

class SqliteDemoPage extends StatefulWidget {
  const SqliteDemoPage({Key? key}) : super(key: key);

  @override
  State<SqliteDemoPage> createState() => _SqliteDemoPageState();
}

class _SqliteDemoPageState extends State<SqliteDemoPage> {
  final DatabaseHelper _dbHelper = DatabaseHelper();
  final TextEditingController _nameController = TextEditingController();
  List<Map<String, dynamic>> _items = [];

  @override
  void initState() {
    super.initState();
    _refreshItems();
  }

  // 查询所有数据
  void _refreshItems() async {
    final data = await _dbHelper.queryAllRows('example');
    setState(() {
      _items = data;
    });
  }

  // 添加数据
  Future<void> _addItem() async {
    await _dbHelper.insert('example', {
      'name': _nameController.text,
    });
    _nameController.clear();
    _refreshItems();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('添加成功！')),
      );
    }
  }

  // 更新数据
  Future<void> _updateItem(int id, String name) async {
    await _dbHelper.update(
      'example',
      {'name': name},
      'id = ?',
      [id],
    );
    _refreshItems();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('更新成功！')),
      );
    }
  }

  // 删除数据
  Future<void> _deleteItem(int id) async {
    await _dbHelper.delete('example', 'id = ?', [id]);
    _refreshItems();
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(content: Text('删除成功！')),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('SQLite Demo'),
      ),
      body: Column(
        children: [
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _nameController,
                    decoration: const InputDecoration(hintText: '请输入名称'),
                  ),
                ),
                ElevatedButton(
                  onPressed: _addItem,
                  child: const Text('添加'),
                ),
              ],
            ),
          ),
          Expanded(
            child: ListView.builder(
              itemCount: _items.length,
              itemBuilder: (context, index) {
                final item = _items[index];
                return ListTile(
                  title: Text(item['name']),
                  trailing: Row(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      IconButton(
                        icon: const Icon(Icons.edit),
                        onPressed: () {
                          showDialog(
                            context: context,
                            builder: (context) {
                              final controller = TextEditingController(
                                text: item['name'],
                              );
                              return AlertDialog(
                                title: const Text('编辑'),
                                content: TextField(controller: controller),
                                actions: [
                                  TextButton(
                                    onPressed: () => Navigator.pop(context),
                                    child: const Text('取消'),
                                  ),
                                  TextButton(
                                    onPressed: () {
                                      _updateItem(item['id'], controller.text);
                                      Navigator.pop(context);
                                    },
                                    child: const Text('保存'),
                                  ),
                                ],
                              );
                            },
                          );
                        },
                      ),
                      IconButton(
                        icon: const Icon(Icons.delete),
                        onPressed: () => _deleteItem(item['id']),
                      ),
                    ],
                  ),
                );
              },
            ),
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    _nameController.dispose();
    super.dispose();
  }
}
